using WebRtcProject.Models.Messages;

namespace WebRtcProject.Services
{
    /// <summary>
    /// WebRTC 专用 RabbitMQ 初始化后台服务
    /// 负责在应用启动时初始化WebRTC专用RabbitMQ连接
    /// </summary>
    public class WebRtcRabbitMQInitializationService : BackgroundService
    {
        private readonly IWebRtcRabbitMQService _webRtcRabbitMQService;
        private readonly ILogger<WebRtcRabbitMQInitializationService> _logger;

        public WebRtcRabbitMQInitializationService(
            IWebRtcRabbitMQService webRtcRabbitMQService,
            ILogger<WebRtcRabbitMQInitializationService> logger)
        {
            _webRtcRabbitMQService = webRtcRabbitMQService;
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                _logger.LogInformation("正在初始化 WebRTC 专用 RabbitMQ 服务...");
                
                // 初始化WebRTC专用RabbitMQ连接
                await _webRtcRabbitMQService.InitializeAsync();
                
                _logger.LogInformation("WebRTC 专用 RabbitMQ 服务初始化完成");

                // 可选：启动设备状态监控
                await StartDeviceStatusMonitoring(stoppingToken);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "WebRTC 专用 RabbitMQ 服务初始化失败");
                // 不抛出异常，让应用继续运行（WebRTC RabbitMQ为可选功能）
            }

            // 保持服务运行
            await Task.Delay(Timeout.Infinite, stoppingToken);
        }

        /// <summary>
        /// 启动设备状态监控（可选功能）
        /// </summary>
        private async Task StartDeviceStatusMonitoring(CancellationToken stoppingToken)
        {
            try
            {
                _logger.LogInformation("开始启动设备状态监控...");

                var statusHandler = new DefaultDeviceStatusHandler(_logger);
                await _webRtcRabbitMQService.StartStatusMonitoringAsync(statusHandler);
                
                _logger.LogInformation("设备状态监控启动成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "启动设备状态监控失败");
            }
        }

        public override void Dispose()
        {
            _webRtcRabbitMQService?.Dispose();
            base.Dispose();
        }
    }

    /// <summary>
    /// 默认设备状态处理器
    /// </summary>
    public class DefaultDeviceStatusHandler : IDeviceStatusHandler
    {
        private readonly ILogger _logger;

        public DefaultDeviceStatusHandler(ILogger logger)
        {
            _logger = logger;
        }

        public async Task HandleDeviceOnlineAsync(string deviceId, DeviceCapabilities capabilities)
        {
            _logger.LogInformation("设备上线: {DeviceId}, 类型: {DeviceType}, 编解码器: {Codecs}", 
                deviceId, capabilities.DeviceType, string.Join(",", capabilities.AudioCodecs));
        }

        public async Task HandleDeviceOfflineAsync(string deviceId, string? reason)
        {
            _logger.LogInformation("设备离线: {DeviceId}, 原因: {Reason}", deviceId, reason ?? "正常离线");
        }

        public async Task HandleDeviceStatusUpdateAsync(DeviceStatusMessage status)
        {
            _logger.LogDebug("设备状态更新: {DeviceId}, 状态: {Status}, 活跃通话: {ActiveCalls}", 
                status.DeviceId, status.Status, status.ActiveCalls);
        }
    }
} 